﻿using ShiQuan.DataRepository;
using ShiQuan.IotDevice.Entity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Linq.Expressions;
using ShiQuan.Utility;

namespace ShiQuan.IotDevice.Business
{
    /// <summary>
    /// 紫外线消毒设备
    /// </summary>
    public class DeviceDataBLL : BasicIotDeviceBLL<DeviceDataEntity>
    {
        /// <summary>
        /// 数据保存
        /// </summary>
        /// <param name="keyValue"></param>
        /// <param name="entity"></param>
        public override void SaveForm(string keyValue, DeviceDataEntity entity)
        {
            if (string.IsNullOrEmpty(entity.SerialNumber))
            {
                throw new Exception("设备唯一标识不能为空！");
            }
            if (string.IsNullOrEmpty(entity.DataId))
            {
                throw new Exception("设备数据标识不能为空！");
            }
            if (string.IsNullOrEmpty(entity.Id))
            {
                entity.Id = Guid.NewGuid().ToString();
                this.Repository.Insert<DeviceDataEntity>(entity);
            }
            else
            {
                entity.Id = keyValue;
                this.Repository.Update<DeviceDataEntity>(entity);
            }
        }
        /// <summary>
        /// 数据保存
        /// </summary>
        /// <param name="source"></param>
        public void SaveData(DeviceDataEntity source)
        {
            if (string.IsNullOrEmpty(source.SerialNumber))
            {
                throw new Exception("设备唯一标识不能为空！");
            }
            if (string.IsNullOrEmpty(source.DataId))
            {
                throw new Exception("设备数据标识不能为空！");
            }
            IRepository db = new RepositoryFactory().BaseRepository(dbContext).BeginTrans();
            try
            {
                DeviceInstallEntity deviceInstall = db.FindEntity<DeviceInstallEntity>(my => my.SerialNumber == source.SerialNumber);
                if (deviceInstall == null)
                    throw new Exception("未能找到设备安装信息！");

                /*2019-12-11 侯连文 根据设备数据标识，判断是否新增或更新*/
                DeviceDataEntity entity = db.FindEntity<DeviceDataEntity>(my => my.DataId == source.DataId);
                if(entity == null)
                    entity = new DeviceDataEntity();

                entity.RefInstallId = deviceInstall.Id;
                entity.RefCorpId = deviceInstall.RefCorpId;
                entity.CorpName = deviceInstall.CorpName;
                entity.RefDeviceId = deviceInstall.RefDeviceId;
                entity.DeviceName = deviceInstall.DeviceName;

                entity.DataId = source.DataId;
                entity.SerialNumber = source.SerialNumber;
                entity.OperatorBy = source.OperatorBy;
                entity.OperatorOn = source.OperatorOn;
                if (entity.OperatorOn != null)
                {
                    entity.Date = entity.OperatorOn.Value.Date;
                    entity.Year = entity.OperatorOn.Value.Year;
                    entity.Month = entity.OperatorOn.Value.Month;
                    entity.Day = entity.OperatorOn.Value.Day;
                    entity.Hour = entity.OperatorOn.Value.Hour;
                    entity.Week = (int)entity.OperatorOn.Value.DayOfWeek;
                }
                entity.Item = source.Item;
                entity.Data = source.Data;
                entity.Unit = source.Unit;
                entity.Text = source.Data + source.Unit;
                entity.Remark = source.Remark;

                entity.CreateDate = DateTime.Now;
                if (string.IsNullOrEmpty(entity.Id))
                {
                    entity.Id = Guid.NewGuid().ToString();
                    db.Insert<DeviceDataEntity>(entity);
                }
                else
                {
                    db.Update<DeviceDataEntity>(entity);
                }

                db.Commit();
            }
            catch (Exception ex)
            {
                db.Rollback();
                throw ex;
            }
        }

        protected override Expression<Func<DeviceDataEntity, bool>> QueryStringToExpression(Expression<Func<DeviceDataEntity, bool>> expression, string queryJson)
        {
            if (string.IsNullOrEmpty(queryJson))
                return expression;
            var queryParam = queryJson.ToJObject();
            if (queryParam["RefCorpId"].IsEmpty() == false && queryParam["RefCorpId"].ToString() != "-1")
            {
                var keyword = queryParam["RefCorpId"].ToString();
                expression = expression.And(my => my.RefCorpId == keyword);
            }
            if (queryParam["RefDeviceId"].IsEmpty() == false && queryParam["RefDeviceId"].ToString() != "-1")
            {
                var keyword = queryParam["RefDeviceId"].ToString();
                expression = expression.And(my => my.RefDeviceId == keyword);
            }
            if (queryParam["RefInstallId"].IsEmpty() == false && queryParam["RefInstallId"].ToString() != "-1")
            {
                var keyword = queryParam["RefInstallId"].ToString();
                expression = expression.And(my => my.RefInstallId == keyword);
            }
            
            if (queryParam["StartDate"].IsEmpty() == false && queryParam["StartDate"].ToString() != "-1")
            {
                var startdate = DateTime.MinValue;
                var keyword = queryParam["StartDate"].ToString();
                DateTime.TryParse(keyword, out startdate);
                if (startdate == DateTime.MinValue)
                    startdate = DateTime.Today;
                expression = expression.And(my => my.Date >= startdate);
            }
            if (queryParam["CloseDate"].IsEmpty() == false && queryParam["CloseDate"].ToString() != "-1")
            {
                var closedate = DateTime.MinValue;
                string keyword = queryParam["CloseDate"].ToString();
                DateTime.TryParse(keyword, out closedate);
                if (closedate == DateTime.MinValue)
                    closedate = DateTime.Today;
                expression = expression.And(my => my.Date <= closedate);
            }
            if (!queryParam["condition"].IsEmpty() && !queryParam["keyword"].IsEmpty())
            {
                string condition = queryParam["condition"].ToString();
                string keyword = queryParam["keyword"].ToString();
                switch (condition)
                {
                    case "OperatorBy":
                        {
                            expression = expression.And(my => my.OperatorBy.Contains(keyword));
                            break;
                        }
                    case "Item":
                        {
                            expression = expression.And(my => my.Item.Contains(keyword));
                            break;
                        }
                    case "DeviceName":
                        {
                            expression = expression.And(my => my.DeviceName.Contains(keyword));
                            break;
                        }
                    default: break;
                }
            }
            return expression;
        }
    }
}
